import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'

import { authWhoAmIScheme } from '@/types/auth.types'

import { AUTH_PAGES, DASHBOARD_PAGES } from '@/config/pages-url.config'

import { EnumStorage } from '@/services/auth-storage.service'

export async function middleware(request: NextRequest) {
	const { url, cookies } = request

	const isLoginPage = url.includes(AUTH_PAGES.LOGIN)

	if (isLoginPage && cookies.get(EnumStorage.ACCESS_TOKEN)) {
		return NextResponse.redirect(new URL(DASHBOARD_PAGES.HOME, url))
	} else if (isLoginPage) {
		return NextResponse.next()
	} else if (!cookies.get(EnumStorage.ACCESS_TOKEN)) {
		return NextResponse.redirect(new URL(AUTH_PAGES.LOGIN, url))
	} else {
		const response = NextResponse.next()
		const redirect_response = NextResponse.redirect(
			new URL(AUTH_PAGES.LOGIN, url)
		)
		redirect_response.cookies.delete(EnumStorage.ACCESS_TOKEN)
		await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/whoami/`, {
			method: 'GET',
			headers: {
				'Content-Type': 'application/json',
				Authorization: `Bearer ${cookies.get(EnumStorage.ACCESS_TOKEN)?.value}`
			}
		})
			.then(async api_response => {
				const data = await api_response.json()
				const user = authWhoAmIScheme.safeParse(data)
				if (user.success)
					response.cookies.set(EnumStorage.USER, JSON.stringify(user.data))
			})
			.catch(error => {
				return redirect_response
			})
		if (response.cookies.has(EnumStorage.USER)) {
			return response
		} else {
			return redirect_response
		}
	}
}

export const config = {
	matcher: ['/d/:path*', `/auth/:path*`]
}
